package com.zhht.htzx;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.data.bean.OrderListBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.BaseAlterDialog;
import com.nsgf.library.utils.ToastUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhht.htzx.adapter.OrderAdapter;
import com.zhht.htzx.databinding.FragmentOrderListBinding;
import com.zhht.htzx.ui.OrderDetailActivity;

import java.util.List;

public class OrderFragment extends BaseFragment {


    public static OrderFragment newInstance(String type) {
        OrderFragment orderFragment = new OrderFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        orderFragment.setArguments(bundle);
        return orderFragment;

    }

    private OrderAdapter orderAdapter;
    private StateHolder mStates;
    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(StateHolder.class);
        mAccountRequester = getFragmentScopeViewModel(AccountRequester.class);
    }


    private FragmentOrderListBinding mBinding;

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        // 设置RecyclerView
        orderAdapter = new OrderAdapter(getActivity());
        return new DataBindingConfig(R.layout.fragment_order_list, BR.vm, mStates)
                .addBindingParam(BR.adapter, orderAdapter);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding = (FragmentOrderListBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);


        initListeners();
        mBinding.swipeRefreshLayout.autoRefresh();

        mAccountRequester.getOrderListResult().observe(this, new Observer<ResponseStatus<OrderListBean>>() {
            @Override
            public void onChanged(ResponseStatus<OrderListBean> orderListBeanResponseStatus) {

                if (page == 1) {
                    mBinding.swipeRefreshLayout.finishRefresh();
                    mStates.orderList.set(orderListBeanResponseStatus.getData().getList());
                    updateEmptyView(mStates.orderList.get().isEmpty());
                } else {
                    mBinding.swipeRefreshLayout.finishLoadMore();

                    List<OrderListBean.ListBean> currentList = mStates.orderList.get();
                    if (currentList != null) {
                        currentList.addAll(orderListBeanResponseStatus.getData().getList());
                        mStates.orderList.set(currentList);
                    }
                }

            }
        });
        mAccountRequester.getSrcSuccess().observe(this, new Observer<ResponseStatus<String>>() {
            @Override
            public void onChanged(ResponseStatus<String> stringResponseStatus) {
                if (stringResponseStatus.getResponseCode() == 0) {
                    ToastUtils.showShortToast(stringResponseStatus.getMsg());
                    mBinding.swipeRefreshLayout.autoRefresh();
//                    if (operationType == 0) {
//                        // 使用保存的订单ID查找位置
//                        int currentPosition = findOrderPosition(currentOrderId);
//                        if (currentPosition != -1) {
//                            List<OrderListBean.ListBean> currentList = mStates.orderList.get();
//                            if (currentList != null) {
//                                ArrayList<OrderListBean.ListBean> newList = new ArrayList<>(currentList);
//                                newList.remove(currentPosition);
//                                mStates.orderList.set(newList);
//                                orderAdapter.submitList(new ArrayList<>(newList));
//                                updateEmptyView(newList.isEmpty());
//                            }
//                        }
//                        // 清除当前操作的订单ID
//                        currentOrderId = null;
//                    } else if (operationType == 1) {
//                        // 使用保存的订单ID查找位置
//                        int currentPosition = findOrderPosition(currentOrderId);
//                        if (currentPosition != -1) {
//                            orderAdapter.getCurrentList().get(currentPosition).setStatus(40);
//                            orderAdapter.notifyItemChanged(currentPosition);
//                        }
//                        // 清除当前操作的订单ID
//                        currentOrderId = null;
//                    } else if (operationType == 2) {
//                        // 使用保存的订单ID查找位置
//                        int currentPosition = findOrderPosition(currentOrderId);
//                        int currentChildPosition = findChildItemOrderPosition(currentChildItemOrderId);
//
//
//                        if (currentPosition != -1) {
//                            orderAdapter.getCurrentList().get(currentPosition).setStatus(40);
//                            orderAdapter.notifyItemChanged(currentPosition);
//                        }
//                        // 清除当前操作的订单ID
//                        currentOrderId = null;
//                    }
                }
            }
        });

    }

    /**
     * 操作类型 0删除 1取消 2申请退款
     */
    private int operationType;
    private String currentOrderId; // 添加变量保存当前操作的订单ID

    private void updateEmptyView(boolean isEmpty) {
        if (isEmpty) {
            mBinding.tvEmpty.setVisibility(View.VISIBLE);
            mBinding.recyclerView.setVisibility(View.GONE);
        } else {
            mBinding.tvEmpty.setVisibility(View.GONE);
            mBinding.recyclerView.setVisibility(View.VISIBLE);
        }
    }

    private String getType() {

        return getArguments().getString("type");
    }

    private void initListeners() {
        // 下拉刷新
        mBinding.swipeRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                page++;
                mAccountRequester.getOrderList(page, getType());
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                page = 1;
                mAccountRequester.getOrderList(page, getType());
            }
        });

        orderAdapter.setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<OrderListBean.ListBean>() {
            @Override
            public void onItemClick(int viewId, OrderListBean.ListBean item, int position) {

                // 跳转到订单详情页
                Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                intent.putExtra("orderId", item.getId());
                startActivity(intent);
            }
        });
        // Tab选择监听
        orderAdapter.setOnClickListener(new OrderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(OrderListBean.ListBean order) {
                // 跳转到订单详情页
                Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                intent.putExtra("orderId", order.getId());
                startActivity(intent);
            }

            @Override
            public void onDeleteClick(OrderListBean.ListBean order, int index) {
                // 删除订单
                operationType = 0;
                currentOrderId = String.valueOf(order.getId());
                mAccountRequester.deleteOrder(currentOrderId);
            }

            @Override
            public void onCancelClick(OrderListBean.ListBean order, int index) {
                // 处理取消订单
                operationType = 1;
                currentOrderId = String.valueOf(order.getId());
                mAccountRequester.cancelOrder(currentOrderId);
            }

            @Override
            public void onConfirmDeliveryClick(OrderListBean.ListBean order) {
                // 处理确认收货
                new BaseAlterDialog(getActivity(), R.style.dialogstyle, "是否确定已收到货？",
                        "确定",
                        "取消",
                        (dialog, confirm) -> {

                            operationType = 3;
                            mAccountRequester.receiveOrder(order.getId());
                            dialog.dismiss();

                        }, new BaseAlterDialog.OnCloseListener() {
                    @Override
                    public void onCancleClick(Dialog dialog, boolean confirm) {
                        dialog.dismiss();
                    }
                }).show();
            }

            @Override
            public void onRefundClick(OrderListBean.ListBean order, OrderListBean.ListBean.ItemsBean childItem) {
                // 处理申请退款
//                handleRefund(order);
                operationType = 2;
                currentOrderId = String.valueOf(order.getId());
                JsonObject params = new JsonObject();
                params.addProperty("orderItemId", childItem.getId());
                params.addProperty("refundPrice", childItem.getPayPrice());
                params.addProperty("way", "10");
                params.addProperty("applyReason", "待发货退款");
                mAccountRequester.refundOrder(params);
            }
        });
    }

    private int page = 1;

}
